﻿# ui/main_window.py
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QTextEdit, QLineEdit,
    QDateEdit, QLabel
)
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtCore import QDate, QObject, pyqtSlot


class ChartBridge(QObject):
    """用于JS与Python通信"""

    @pyqtSlot(str)
    def update_chart(self, json_data):
        """接收JS端消息（调试用）"""
        print("JS received data:", json_data)


def init_web_view(self):
    """初始化支持WebChannel的HTML"""
    channel = QWebChannel()
    self.bridge = ChartBridge()
    channel.registerObject("pyBridge", self.bridge)

    self.web_view.page().setWebChannel(channel)

    html = """
    <html>
    <head>
        <script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
        <script>
            var fig = {data: [], layout: {}, config: {}};
            window.pyBridge = null;

            // 等待WebChannel就绪
            new QWebChannel(qt.webChannelTransport, function(channel) {
                window.pyBridge = channel.objects.pyBridge;
                console.log("WebChannel ready");
                // 初始化空图
                Plotly.newPlot('chart', fig.data, fig.layout, {responsive: true});
            });

            // 更新图表
            function updateKline(dataJson) {
                try {
                    var data = JSON.parse(dataJson);
                    var traces = data.traces;

                    // 使用 Plotly.react 进行高效更新（避免重绘）
                    Plotly.react('chart', traces, data.layout);
                } catch(e) {
                    console.error("Update error:", e);
                }
            }
        </script>
    </head>
    <body style="margin:0;padding:0;background:#1e1e1e;color:#fff;font-family:Arial">
        <div id="chart" style="width:100%;height:600px;"></div>
    </body>
    </html>
    """
    self.web_view.setHtml(html)